<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学员姓名" prop="memberUserRealName">
        <el-input
          v-model="queryParams.memberUserRealName"
          placeholder="请输入学员姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学员性别" prop="memberUserSex">
        <el-select v-model="queryParams.memberUserSex" placeholder="请选择学员性别" clearable>
          <el-option
            v-for="dict in dict.type.member_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="queryParams.userType" placeholder="请选择用户类型" clearable>
          <el-option
            v-for="dict in dict.type.user_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="memberUserManagementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="用户照片" align="center" width="80">
        <template slot-scope="scope">
          <div style="padding-top: 100%; position: relative;">
            <!-- 图片回显 -->
            <ImagePreview :src="String(scope.row.memberUserPhoto)"
                          style="position: absolute; top: 0; left: 0; bottom: 0; right: 0;"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="学员手机号" align="center" prop="memberUserPhone"/>
      <el-table-column label="学员姓名" align="center" prop="memberUserRealName"/>
      <el-table-column label="学员性别" align="center" prop="memberUserSex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.member_user_sex" :value="scope.row.memberUserSex"/>
        </template>
      </el-table-column>
      <el-table-column label="学员年龄" align="center" prop="memberUserAge"/>
      <el-table-column label="学员体重" align="center" prop="memberUserWeight"/>
      <el-table-column label="学员身高" align="center" prop="memberUserHeight"/>
      <el-table-column label="体脂率" align="center" prop="memberUserBodyFat"/>
      <el-table-column label="会员卡编号" align="center" prop="membershipCardNumber"/>
      <el-table-column label="用户类型" align="center" prop="userType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user_type" :value="scope.row.userType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleSelect(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <!--          <el-button-->
          <!--            v-if="scope.row.userType === 1"-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-plus"-->
          <!--            @click="addLesson(scope.row)">-->
          <!--            续课-->
          <!--          </el-button>-->
          <!--          <el-button-->
          <!--            v-if=""-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-minus"-->
          <!--            @click="dropLesson(scope.row)"-->
          <!--          >退课-->
          <!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会员用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body @close="clearData">
      <el-form
        ref="form"
        :model="form"
        label-width="130px"
        :rules="rules"
        class="form-container"
        :inline="true"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="照片:" prop="memberUserPhoto">
              <el-button type="text" @click="openCamera">打开摄像头拍照</el-button>
              <br>
              <el-dialog :visible.sync="showCameraDialog" width="600px">
                <video width="550px" ref="video" autoplay></video>
                <canvas ref="canvas" style="display: none;"></canvas>
                <br>
                <el-button type="primary" @click="takePhoto">拍照</el-button>
              </el-dialog>

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <img
              height="210"
              v-if="memberUserPhoto1"
              :src="memberUserPhoto1"
              class="avatar"
            />
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="memberUserRealName">
              <el-input v-model="form.memberUserRealName" placeholder="请输入名称" style="width: 200px;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="memberUserPhone">
              <el-input v-model="form.memberUserPhone" placeholder="请输入手机号"
                        oninput="value=value.replace(/[^0-9.]/g,'')" style="width: 200px;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="memberUserSex">
              <el-radio-group v-model="form.memberUserSex" size="medium">
                <el-radio :label="0">男</el-radio>
                <el-radio :label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="memberUserAge">
              <el-input v-model="form.memberUserAge" placeholder="请输入年龄"
                        oninput="value=value.replace(/[^0-9.]/g,'')" style="width: 200px;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="身高(cm)" prop="memberUserHeight">
              <el-input-number
                v-model="form.memberUserHeight"
                placeholder="请输入身高"
                :min="50"
                :max="250"
                controls-position="right"
                style="width: 200px;"
              >
                <template #append>cm</template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体重(kg)" prop="memberUserWeight">
              <el-input-number
                v-model="form.memberUserWeight"
                placeholder="请输入用户体重"
                :min="30"
                controls-position="right"
                style="width: 200px;"
              >
                <template #append>kg</template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="卡号" prop="membershipCardNumber">
              <el-input v-model="form.membershipCardNumber" placeholder="请输入会员卡编号" style="width: 200px;"
                        disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卡的类型" prop="memberTypeId">
              <el-select v-model="form.memberType" placeholder="请输卡名称">
                <el-option v-for="item in memberList" :key="item.id" :label="item.memberTypeName" :value="item.memberType"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.memberType == 0">
          <el-col :span="12">
            <el-form-item label="卡可用次数" prop="availableTimes">
              <el-input v-model="form.availableFrequency" placeholder="请输入卡可用次数"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-else>
          <el-col :span="12">
            <el-form-item label="卡有效期限" prop="serviceLife">
              <el-input v-model="form.cardDays" placeholder="请输入卡有效期限"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 点击按钮显示外置弹窗 -->
      <el-button icon="el-icon-plus" @click="saveCoach" circle>选择教练</el-button>
      <!-- 显示已选教练信息的表格 -->
      <el-table :data="coachMessage">
        <el-table-column label="教练名称" align="center" prop="coachName"/>
        <el-table-column label="教练性别" align="center" prop="coachSex">
          <template slot-scope="scope">
            {{ scope.row.coachSex === 0 ? '女' : '男' }}
          </template>
        </el-table-column>
        <el-table-column label="总课时" align="center" prop="courseTime">
          <!-- 输入总课时的文本框 -->
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.courseTime"
              placeholder="请输入总课时"
              size="small"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="已上课时" align="center" prop="afterClass"/>
        <!-- 删除按钮列 -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="deleteCoach(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 内置弹窗，用于选择教练 -->
      <el-dialog
        width="800px"
        title="添加教练"
        :visible.sync="innerVisible"
        append-to-body
      >
        <el-table v-loading="loading" :data="couchList" @selection-change="handleSelectionChange" ref="multipleTable"
                  v-model="selectedCoaches"
        >
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="教练名称" align="center" prop="coachName"/>
          <el-table-column label="教练性别" align="center" prop="coachSex">
            <template slot-scope="scope">
              {{ scope.row.coachSex === 0 ? '女' : '男' }}
            </template>
          </el-table-column>
        </el-table>
        <br>
        <!-- 确定和关闭按钮 -->
        <div style="margin-left: 550px">
          <el-button type="primary" @click="definiteAddition">添 加</el-button>
          <el-button @click="Off">关 闭</el-button>
        </div>
      </el-dialog>
      <!-- 外置弹窗，展示已选教练信息 -->
      <el-dialog
        width="800px"
        title="选择教练"
        :visible.sync="outerVisible"
        append-to-body
        @close="clearData"
      >
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelPopup">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户信息详情 -->
    <el-dialog :visible.sync="isShow" width="40%" append-to-body>
      <div>
        <el-descriptions title="用户信息" class="margin-top" :column="3" border>
          <el-descriptions-item>
            <template slot="label">
              用户头像
            </template>
            <ImagePreview class="image-preview" :src="String(userInfomationList.memberUserPhoto)"/>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i>
              用户名
            </template>
            <span class="tooltip-text">{{ userInfomationList.memberUserRealName }}</span>
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-mobile-phone"></i>
              手机号
            </template>
            {{ userInfomationList.memberUserPhone }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-mobile-phone"></i>
              年龄
            </template>
            {{ userInfomationList.memberUserAge }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              性别
            </template>
            {{ userInfomationList.memberUserSex === 0 ? '男' : '女' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              身高
            </template>
            {{ userInfomationList.memberUserHeight === 0 ? '暂无数据' : userInfomationList.memberUserHeight + 'cm' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              体重
            </template>
            {{ userInfomationList.memberUserWeight === 0.00 ? '暂无数据' : userInfomationList.memberUserWeight + 'kg' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              体脂率
            </template>
            {{
              userInfomationList.memberUserBodyFat === 0.00 ? '暂无数据' : userInfomationList.memberUserBodyFat + '%'
            }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              开通时间
            </template>
            {{ userInfomationList.createTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              教练
            </template>
            {{
              userInfomationList.invitationCode === null || userInfomationList.invitationCode === 'null' ? '暂无' : userInfomationList.coachName
            }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div style="margin-top: 30px;">
        <el-descriptions title="会员信息" :column="3" border>
          <el-descriptions-item>
            <template slot="label">
              会员卡卡号
            </template>
            {{
              userInfomationList.membershipCardNumber === null || userInfomationList.membershipCardNumber === '' ? '暂未绑定' : userInfomationList.membershipCardNumber
            }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              会员类型
            </template>
            {{ userInfomationList.memberType === 0 ? '次卡' : '期限卡' }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              会员卡名称
            </template>
            {{ userInfomationList.memberTypeName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              {{ userInfomationList.memberType === 0 ? '可用次数' : '到期时间' }}
            </template>
            {{
              userInfomationList.memberType === 0 ? userInfomationList.availableFrequency + '次' : userInfomationList.cardDays
            }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              会员备注
            </template>
            {{ userInfomationList.memberTypeRemarks }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="button-container" style="text-align: right;">
        <el-button type="primary" @click="cancell">确定</el-button>
      </div>
    </el-dialog>
    <!--    续课退课弹窗-->
    <!--    <el-dialog :title="lesson" :visible.sync="showLesson" width="900px" append-to-body>-->
    <!--        <el-table v-loading="loading" :data="lessonData">-->
    <!--          <el-table-column label="教练名称" align="center" prop="coachName"/>-->
    <!--          <el-table-column label="教练性别" align="center" prop="coachSex">-->
    <!--            <template slot-scope="scope">-->
    <!--              {{ lessonData.coachSex === 0 ? '女' : '男' }}-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--          <el-table-column label="课程" align="center" prop="name"/>-->
    <!--          <el-table-column label="总课时" align="center" prop="courseTime"/>-->
    <!--          <el-table-column label="已上课时" align="center" prop="afterClass"/>-->
    <!--          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
    <!--            <template slot-scope="scope">-->
    <!--              <el-button size="mini" type="text" @click="addLessonClass(scope.row)">选择</el-button>-->
    <!--            </template>-->
    <!--          </el-table-column>-->
    <!--          <el-table-column :label="hour">-->
    <!--            <template slot-scope="scope">-->
    <!--              <div v-if="selectedRow && selectedRow === scope.row">-->
    <!--                <el-input v-model="courseTime" placeholder="请输入课时数量"></el-input>-->
    <!--                <el-button size="mini" type="primary" @click="confirmAddLesson(scope.row)">确认</el-button>-->
    <!--                <el-button size="mini" type="text" @click="cancelAddLesson">取消</el-button>-->
    <!--              </div>-->
    <!--            </template>-->
    <!--          </el-table-column>-->

    <!--        </el-table>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>
import {
  listMemberUserManagement,
  getById,
  getMemberUserManagement,
  delMemberUserManagement,
  addMemberUserManagement,
  updateMemberUserManagement,
  ifMemberCardBind
} from '@/api/memberUserManagement/memberUserManagement'
import { getCouchInfo } from '@/api/subscribe/courseSubscribe'
import { listManagement } from '@/api/memberTypeManagement/management'
import { deleteByCoachId, memberCoachById, addCourseTime, refundCourseTime } from '@/api/memberCoach/memberCoach'

export default {
  name: 'MemberUserManagement',
  dicts: ['member_user_sex', 'user_type', 'online_status'],
  data() {
    return {
      receivedMessage: '',
      //用户状态
      userType: '',
      //课时名称
      hour: '',
      selectedRow: null, // 存储用户选中的行数据
      courseTime: '', // 保存用户输入的课时信息
      //续课选择课程弹窗
      extendTheClass: false,
      //续课退课弹窗数据
      lessonData: [],
      //续课退课弹窗名字
      lesson: '',
      //续课退课弹窗
      showLesson: false,
      // 下拉框状态
      statusChange: '',
      //会员类型信息
      memberList: [],
      //储存教练信息
      coachMessage: [],
      //暂时储存教练信息
      temporarilyCoach: [],
      //选择好的教练信息
      selectedCoaches: [],
      innerVisible: false,  // 控制内置弹窗显示
      outerVisible: false,  // 控制外置弹窗显示
      // 详情信息回显
      userInfomationList: {},
      // 用户详情弹出框
      isShow: false,
      // 图片回显
      memberUserPhoto1: '',
      // 拍照弹出框
      showCameraDialog: false,
      // 租户标识
      venueUniqueIdentifier: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员用户表格数据
      memberUserManagementList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        memberUserRealName: null,
        memberUserSex: null,
        userType: null
      },
      //教练查询数据
      couchList: [],
      // 表单参数
      form: {
        //用来存放课程和教练的数据
        courseAndCoachData: [{}]
      },
      rules: {
        memberUserRealName: [{ required: true, message: '请输入用户名称', trigger: 'blur' }, {
          max: 25,
          message: '最大字符为25',
          trigger: 'blur'
        }],
        memberUserPhone: [{ required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^\d{11}$/, message: '手机号必须是11位数字', trigger: 'blur' }],
        memberUserSex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        memberUserAge: [{ required: true, message: '请输入年龄', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const age = parseInt(value)
              if (Number.isInteger(age) && age > 0) {
                callback()
              } else {
                callback(new Error('年龄必须为正整数'))
              }
            },
            trigger: 'blur'
          }],
        memberUserHeight: [{ required: true, message: '请输入用户身高', trigger: 'blur' },
          { type: 'number', message: '身高必须为数字', trigger: 'blur' }],
        memberUserWeight: [{ required: true, message: '请输入用户体重', trigger: 'blur' },
          { type: 'number', message: '体重必须为数字', trigger: 'blur' }]
      }
    }
  },
  watch: {
    // 在 receivedMessage 变化时执行指定的方法
    receivedMessage(newVal) {
      this.handleReceivedMessage(newVal)
      console.log(newVal)
      this.coachNames = []
    },
    // 监听下拉框是否变化
    'form.memberType': function(newVal) {
      //判断卡次数或期限
      this.handleStatusChange(newVal)
    }
  },
  created() {
    this.getList()
    // 在页面进入时创建 WebSocket 连接
    this.ws = new WebSocket('ws://localhost:8080/wsReadCard/123123')
    // 监听 WebSocket 连接打开事件
    this.ws.onopen = () => {
      console.log('WebSocket connected 录入卡号')
    }

    // 监听 WebSocket 收到消息事件
    this.ws.onmessage = (event) => {
      // debugger
      this.receivedMessage = event.data
    }
  },
  methods: {
    handleMemberTypeChange() {
      const selectedId = this.form.typeId
      if (selectedId !== null) {
        const selectedItem = this.memberList.find(item => item.id === selectedId)
        if (selectedItem) {
          console.log(`Selected member type ID: ${selectedItem.id}`)
          console.log(`Selected member type name: ${selectedItem.memberTypeName}`)
          // Perform further actions with selected item
        }
        this.form.typeId = selectedItem.id
      }
    },
    // 判断下拉框
    handleStatusChange(memberType) {
      this.form.memberType = memberType
      console.log(memberType)
    },
    // websocket数据变化时进行查询
    handleReceivedMessage(message) {
      const parsedMessage = JSON.parse(message)
      const cardNum = parsedMessage.cardNum
      //判断会员卡是否绑定会员
      ifMemberCardBind(cardNum).then((res) => {
        if (res.data > 0) {
          this.$message.error('该会员卡已绑定,请换卡!')
        } else {
          this.form.membershipCardNumber = cardNum
        }
      })

    },
    // 点击选择按钮时，显示该行的添加课时输入框
    addLessonClass(row) {
      this.selectedRow = row
    },
    // 点击确认按钮时，执行添加课时的逻辑
    // 使用this.courseTime保存用户输入的课时信息并处理相应逻辑
    confirmAddLesson(row) {
      if (this.hour === '添加课时') {
        row.courseTime = this.courseTime
        addCourseTime(row).then((response) => {
          this.$modal.msgSuccess('续课成功')
          console.log(row)
          this.loading = false
          this.showLesson = false
        })
        // 添加完成后，隐藏输入框并清空输入内容
        this.selectedRow = null
        this.courseTime = ''
      } else if (this.hour === '退课') {
        if (this.courseTime - row.afterClass < row.courseTime) {
          this.$modal.msgError('退课失败，您已经上' + row.afterClass + '节课，不能全部退课')
        } else {
          row.courseTime = this.courseTime
          refundCourseTime(row).then((response) => {
            this.$modal.msgSuccess('退课成功')
            console.log(row)
            this.loading = false
            this.showLesson = false
          })
          // 添加完成后，隐藏输入框并清空输入内容
          this.selectedRow = null
          this.courseTime = ''
        }
      }
    },
    cancelAddLesson() {
      // 点击取消按钮时，隐藏输入框并清空输入内容
      this.selectedRow = null
      this.courseTime = ''
    },
    //课时数据查询
    addLesson(row) {
      this.showLesson = true
      this.hour = '添加课时'
      memberCoachById(row.id).then((response) => {
        this.lessonData = response.data
        console.log(response.data)
        this.loading = false
      })
    },
    //退课
    // dropLesson(row){
    //   this.hour = "退课"
    //   this.showLesson = true;
    //   memberCoachById(row.id).then((response) => {
    //     this.lessonData = response.data;
    //     console.log(response.data)
    //     this.loading = false
    //   })
    // },
    // 删除教练信息
    deleteCoach(row) {
      console.log('添加')
      const index = this.coachMessage.indexOf(row)
      if (index !== -1) {
        this.coachMessage.splice(index, 1)
      }
      // 同时从已选中教练数组中移除
      const selectedIndex = this.selectedCoaches.indexOf(row)
      if (selectedIndex !== -1) {
        this.selectedCoaches.splice(selectedIndex, 1)
      }
    },
    // 保存教练信息，显示内置弹窗
    saveCoach() {
      this.innerVisible = true
      this.loading = true
      // 调用接口获取教练列表
      getCouchInfo().then(response => {
        this.couchList = response.data
        // 等待 DOM 更新完成后再进行勾选操作
        this.$nextTick(() => {
          // 保持上次选择的教练状态
          this.couchList.forEach(coach => {
            if (this.selectedCoaches.some(selected => selected.id === coach.id)) {
              this.$refs.multipleTable.toggleRowSelection(coach, true)
            }
          })
          this.loading = false
        })
      })
    },
    // 确定添加教练
    definiteAddition() {
      this.$message.success('选择成功')
      this.selectedCoaches = [...this.temporarilyCoach]
      // 为每个教练附上默认总课时
      this.selectedCoaches.forEach(coach => {
        if (!coach.courseTime) {
          this.$set(coach, 'courseTime', 12)
        }
        if (!coach.afterClass) {
          this.$set(coach, 'afterClass', 0)
        }
      })
      this.coachMessage = [...this.selectedCoaches]
      this.innerVisible = false
    },
    // 选择教练变化处理
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.temporarilyCoach = selection
    },
    // 关闭内置弹窗
    Off() {
      this.innerVisible = false
    },
    // 取消选择教练
    cancelPopup() {
      this.outerVisible = false
      this.open = false
      this.clearData()
    },
    // 清空所有数据
    clearData() {
      this.coachMessage = []
      this.temporarilyCoach = []
      this.selectedCoaches = []
    },
    // 打开摄像头
    openCamera() {
      this.showCameraDialog = true
      navigator.mediaDevices.getUserMedia({ video: true })
        .then((stream) => {
          const video = this.$refs.video
          video.srcObject = stream
          video.play()
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // 拍照并调用方法处理
    takePhoto() {
      const canvas = this.$refs.canvas
      const context = canvas.getContext('2d')
      const video = this.$refs.video
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      context.drawImage(video, 0, 0, canvas.width, canvas.height)
      const dataURL = canvas.toDataURL('image/jpeg')

      // 创建一个Blob对象来代表照片文件
      const blob = this.dataURLtoBlob(dataURL)
      blob.lastModifiedDate = new Date()
      blob.name = 'photo.jpg'

      // this.addForm.memberUserPhoto = blob; // 将照片文件赋值给表单字段
      // console.log(this.addForm.memberUserPhoto)
      this.beforeAvatarUpload(blob)
      this.showCameraDialog = false
    },
    // 对拍到的照片进行处理
    dataURLtoBlob(dataURL) {
      const byteString = atob(dataURL.split(',')[1])
      const mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0]
      const ab = new ArrayBuffer(byteString.length)
      const ia = new Uint8Array(ab)
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ab], { type: mimeString })
    },
    // 文件上传校验
    beforeAvatarUpload(file) {
      //上传图片格式
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是JPG/PNG格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过2MB!')
        return false
      }
      //赋值
      this.addimages = file
      this.memberUserPhoto1 = URL.createObjectURL(file)
      //isJPG && isLt2M 自动提交 false 是点击确定后提交
      return false
    },
    /** 查询会员用户列表 */
    getList() {
      this.loading = true
      listMemberUserManagement(this.queryParams).then(response => {
        this.memberUserManagementList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    //查询会员卡类型
    selectMemberType() {
      listManagement().then(response => {
        this.memberList = response.rows
        console.log(this.memberList)
      })
    },
    // 查询一条操作
    handleFind(row) {
      this.title = '查看会员类型信息'
      this.loading = true
      this.shaoSaveButton = false
      getById(row.id).then((res) => {
        this.form = res.data
        console.log(this.form)
        this.memberUserPhoto1 = process.env.VUE_APP_IMG_BASE_URL + res.data.memberUserPhoto
        this.loading = false
        this.userInfomationList = res.data
        console.log(res.data)
        if (this.form.memberType === 0 && this.form.availableTimes !== 0) {
          this.isUpdateMode = true
        } else if (this.form.memberType === 1 && this.form.expirationTime) {
          const expirationTime = Date.parse(this.form.expirationTime) // 将日期字符串转换成时间戳
          const now = Date.now() // 获取当前时间的时间戳
          if (expirationTime > now) {
            this.isUpdateMode = true
          }
        } else {
          this.isUpdateMode = false
        }
      })
    },
    // 详情确认按钮
    cancell() {
      this.isShow = false
      this.memberUserManagementList = {}
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 详情显示
    handleSelect(row) {
      this.title1 = '用户信息'
      this.handleFind(row)
      this.isShow = true
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        venueUniqueIdentifier: null,
        fitnessPlanId: null,
        memberUserPhone: null,
        memberUserRealName: null,
        memberUserAge: null,
        memberUserWeight: 70,
        memberUserHeight: 170,
        memberUserBodyFat: null,
        memberUserName: null,
        memberUserHeard: null,
        memberUserPhoto: null,
        invitationCode: null,
        createTime: null,
        updateTime: null,
        delFlag: null,
        membershipCardNumber: null,
        isAllocation: null,
        onlineStatus: null,
        onlineTimes: null,
        coachNotes: null,
        userType: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.form.memberUserSex = 0
      this.title = '添加会员用户'
      this.selectMemberType()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.selectMemberType()
      this.reset()
      this.open = true
      this.title = '修改会员用户'
      const id = row.id || this.ids
      this.handleFind(row)
      //查询vip私教会员的教练
      memberCoachById(id).then(response => {
        this.form.courseAndCoachData = response.data
        this.coachMessage = this.form.courseAndCoachData
        console.log(this.form.courseAndCoachData)
        this.loading = false
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.outerVisible = false
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 将 this.courseAndCoach 存入 this.form 中
            this.form.courseAndCoachData = this.coachMessage
            console.log(this.form.courseAndCoachData)
            if (this.coachMessage.length > 0) {
              this.form.userType = 1
            } else {
              this.form.userType = 0
            }
            updateMemberUserManagement(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            // 将 this.courseAndCoach 存入 this.form 中
            this.form.courseAndCoachData = this.coachMessage
            console.log(this.form.courseAndCoachData)
            if (this.coachMessage.length > 0) {
              this.form.userType = 1
            } else {
              this.form.userType = 0
            }
            addMemberUserManagement(this.form).then(response => {
              console.log(this.form)
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除会员用户编号为"' + ids + '"的数据项？').then(function() {
        return delMemberUserManagement(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('memberUserManagement/memberUserManagement/export', {
        ...this.queryParams
      }, `memberUserManagement_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
